package com.sl.plugin.step.object;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import com.sl.core.engine.step.rowfrom.ProcessCompPutRowFrom;
import com.sl.core.engine.step.rowfrom.ProcessCompPutRowFromConfig;
import com.sl.core.engine.utils.BeanUtil;
import org.apache.commons.compress.utils.Lists;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 */
//@Compensation(listener = NormalRowListener.class, type = CompensationType.SERVICE_COMPENSATION)
public class ObjectMergeComp extends AbstractProcessComp<ProcessCompPutRowFrom, Map<String, Object>> implements ProcessCompService {

    public ObjectMergeComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }


    @Override
    public Map<String, Object> input(ProcessCompPutRowFrom param) {

        List<Map<String, Object>> listMapAttr = meta.getListMapAttr("config.output");
        if (CollUtil.isEmpty(listMapAttr)) {
            return null;
        }
        Map<String, Object> root = Maps.newLinkedHashMap();
        for (Map<String, Object> map : listMapAttr) {
            String fromTransformName = BeanUtil.getStr(map, "fromTransformName");
            String str = BeanUtil.getStr(map, "newFromTransformName");
            Boolean bool = BeanUtil.getBool(map, "outputDefine.isArrayFlag");
            List o = findListData(param, fromTransformName);
            Object put = o;
            if (BooleanUtil.isFalse(bool)) {
                put = CollUtil.getLast(o);
            }
            if (StrUtil.isBlank(str)) {
                if (put instanceof Collection<?> cl) {
                    for (Object object : cl) {
                        if (object instanceof Map m) {
                            root.putAll(m);
                        }
                    }

                } else if (put instanceof Map m) {
                    root.putAll(m);
                }
            } else {
                root.put(str, put);
            }


        }

        return root;
    }

    private List<Object> findListData(ProcessCompPutRowFrom param, String fromTransformName) {

        List<ProcessCompPutRowFromConfig> configList = param.getConfigList();
        List<Object> res = Lists.newArrayList();
        for (ProcessCompPutRowFromConfig processCompPutRowFromConfig : configList) {
            Object data1 = processCompPutRowFromConfig.getData();
            if (StrUtil.equalsAnyIgnoreCase(processCompPutRowFromConfig.getFromTransformName(), fromTransformName)) {
                res.addAll(BeanUtil.convert(data1));
            }
        }
        return res;
    }
}
